﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using XLua;
using System.IO;

public class LuaManager : MonoBehaviour
{
    public bool startYet = false;

    private static LuaManager _Instance;
    public static LuaManager Instance
    {
        get
        {
            return _Instance;
        }
    }
    private void Awake()
    {
        _Instance = this;
        _luaEnv = new LuaEnv();
        _luaEnv.AddLoader((ref string filePath) =>
        {
            var newPath = Path.Combine(Application.dataPath, "../LuaCode/" + filePath + ".lua");
            var con = File.ReadAllText(newPath);
            filePath = filePath + ".lua";
            return System.Text.Encoding.UTF8.GetBytes(con);
            //return ABLoader.Instance.LoadLua(filePath);
        });
        InitLua();
    }

    public void InitLua()
    {
        _luaEnv.DoString(@"
            require 'Main'
        ");
        //_luaEnv.Global.Get("DoFile", out RequireFile);
        //_luaEnv.Global.Get("DoModule", out DoModule);
        startYet = true;
    }

    public static void LoadAndDoFile(string filePath)
    {
        var newPath = Path.Combine(Application.dataPath, "../LuaCode/" + filePath + ".lua");
        var con = File.ReadAllText(newPath);
        var bytes = System.Text.Encoding.UTF8.GetBytes(con);
        luaEnv.DoString(bytes);
    }

    /*
    //[CSharpCallLua]
    public delegate void S_VDel(string s1);
    //[CSharpCallLua]
    public delegate LuaTable S_TDel(string s1);
    public static S_VDel RequireFile;
    public static S_TDel DoModule;
    */

    private static LuaEnv _luaEnv;
    public static LuaEnv luaEnv
    {
        get
        {
            if(_luaEnv == null)
            {
                var go = new GameObject("XLua");
                GameObject.DontDestroyOnLoad(go);
                go.AddComponent<LuaManager>();
            }
            return _luaEnv;
        }
    }
}
